//index.js
var func = require('../../utils/func.js');
var net = require('../../utils/ajax.js');
var url = require('../../utils/url.js');
var user = require('../../utils/user.js');
var Promise = require('../../libs/promise.js');

var event = require('../../utils/eventManager.js');

let app = getApp();
let me;
let uid;
let firstLoad = true;

let login = (code, iv, encryptedData) => {
  return net.send(url.login, {
    code: code,
    iv: iv,
    encryptedData: encryptedData
  }).then(res => {
    if (!!res.info) {
      user.userInfo.code = code;
      user.setUserInfo(res.info);
      uid = res.info.uid;
    } else {
      console.log("登陆失败!")
    }
  }).then(() => {
    if (!!uid) {
      getDrafts();
      getPublished();
    }
  }).then(() => {
    firstLoad = false;
  })
}

let getDrafts = () => {
  net.send(url.getDraftList, {
    uid: uid
  }).then(res => {
    if (!!res.info.length) {
      func.setStorge("drafts_" + uid.toString(), res.info);

      let draft = res.info[0];
      draft.time = func.dateFormat(res.info[0].last_update_time, "yyyy-MM-dd");

      me.setData({
        draft: draft,
        draftCount: res.info.length.toString()
      })
    } else {
      me.setData({
        draft: {},
        draftCount: res.info.length.toString()
      })
    }

    //console.log(res);
  })
}

let getPublished = () => {
  net.send(url.getPublishedArticle, {
    uid: uid
  }).then(res => {
    if (!!res.info.length && res.status == "y") {
      func.setStorge("articles_" + uid.toString(), res.info);
      me.setData({
        publishCount: res.info.length.toString()
      })
    } else {
      me.setData({
        publishCount: res.info.length.toString()
      })
    }
  })
};

let refreshData = () => {
  if (!uid) return;
  getDrafts();
  getPublished();
}

//获取应用实例
Page({
  data: {
    draft: {},
    draftCount: "",
    publishCount: "",
    loadReady: false
  },
  toList(e) {
    let type = e.currentTarget.dataset.type;

    if (type == "draft" && this.data.draftCount == "0") {
      func.showToast("还没有草稿!", "loading");
      return;
    }

    if (type == "publish" && this.data.publishCount == "0") {
      func.showToast("还未发布文章!", "loading");
      return;
    }

    func.navigateTo("../listPage/listPage?type=" + type);
  },
  toEdit(e) {
    let id = e.currentTarget.dataset.id;
    func.navigateTo("../articleEdit/articleEdit?id=" + id);
  },
  onLoad() {
    me = this;
    app.getUserInfo((info, secret, code) => {
      func.loading(login(code, secret.iv, secret.encryptedData), me);
    });
    event.listenEvent("refreshMain", function () {
      refreshData();
    })
  },
  onShow() {
  },
  onPullDownRefresh() {
    refreshData();
    wx.stopPullDownRefresh();
  }
})